package com.gopay.scheduler.job;

import com.gopay.common.constants.proccode.ProcCodeConstants;
import com.gopay.common.constants.trans.OrderType;
import com.gopay.common.constants.trans.PayBankAsyncOpType;
import com.gopay.common.constants.trans.Trans00700AssistStatus;
import com.gopay.common.constants.trans.TxnStaCode;
import com.gopay.common.constants.txncd.IntTxnCd;
import com.gopay.common.cps.dao.order.CpsGeneralMainOrderQueryDAO;
import com.gopay.common.cps.dao.order.CpsTran00700AssistDAO;
import com.gopay.common.domain.cps.CpsGenMainOrder;
import com.gopay.common.domain.cps.CpsGenManageOrder;
import com.gopay.common.domain.cps.CpsTrans00700Assist;
import com.gopay.common.domain.cps.transfer.Tran00700AsyncVO;
import com.gopay.common.domain.cps.vo.CPSResponse;
import com.gopay.common.exception.GopayException;
import com.gopay.remote.order.MainOrderUpdateRemoteService;
import com.gopay.scheduler.GopayBaseJob;
import com.gopay.scheduler.common.CallCPSHelper;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.annotation.Resource;
import java.util.*;

/**
 *
 * 00700 异步消费
 * @author ddh02
 * @Tran00700AsyncJob
 * @2017/7/27 21:27  www.gopay.com.cn Inc.All rights reserved.
 */

public class Tran00700AsyncJob extends GopayBaseJob {

    private Logger logger = LoggerFactory.getLogger(Tran00700AsyncJob.class);
    private CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO;
    private MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient;

    private static final int QUERYCOUNT = 200;

    private String switch00700; //cron 是否跑的开关 --不用加开关  空跑就行

    private static final int txnStaCd = TxnStaCode.TXN_STA_CD_30000.value;
    private static final String gopayIntTxnCd = IntTxnCd._00700.value;

    @Resource(name = "cpsGeneralMainOrderOperClient")
    public void setCpsGeneralMainOrderOperClient(MainOrderUpdateRemoteService cpsGeneralMainOrderOperClient) {
        this.cpsGeneralMainOrderOperClient = cpsGeneralMainOrderOperClient;
    }

    @Resource(name = "cpsGeneralMainOrderDAO")
    public void setCpsGeneralMainOrderDAO(CpsGeneralMainOrderQueryDAO cpsGeneralMainOrderDAO) {
        this.cpsGeneralMainOrderDAO = cpsGeneralMainOrderDAO;
    }


    @Resource(name = "cpsTran00700AssistDAO")
    private CpsTran00700AssistDAO tran00700AssistDAO;

    @Resource(name = "callCPSHelper")
    private CallCPSHelper callCPSHelper;

    @Override
    protected void doJobInternal() {


        if (true) {
            logger.error("单线程处理模式 暂时屏蔽掉 ， 使用多线程模式跑，请勿配置错误！！！");
            return;
        }


        long startMillions = System.currentTimeMillis();
        logger.info("00700 异步处理开始 ");

        String sql = "from CpsTrans00700Assist t where " +
                "t.status= '" + Trans00700AssistStatus.INIT.value +"'" +
                // " or ( t.status=:status02 and t.createdTs <=:date) " +
                "and t.createdTs >= :date1";

        Map<String, Object> map = new HashMap();
        //map.put("status1", Trans00700AssistStatus.INIT.value);


        //date1 多久时间内的数据
        Date date1 = new Date();
        Calendar calendar1 = Calendar.getInstance();
        calendar1.setTime(date1);
        calendar1.add(Calendar.DAY_OF_YEAR, -1);  //减一天
        date1 = calendar1.getTime();
        map.put("date1", date1);

        //List<CpsGenMainOrder> orderList = cpsGeneralMainOrderDAO.findBySql("sql", map, 1 , QUERYCOUNT);

        List<CpsTrans00700Assist> assists = tran00700AssistDAO.findByHql(sql, map, 1, QUERYCOUNT);

        callCps(assists);

        long endMiilions = System.currentTimeMillis();
        long result = (endMiilions - startMillions) / 1000;
        logger.info("00700 异步处理结束 耗费=" + result + "秒");

    }

    private void callCps(List<CpsTrans00700Assist> assists)  {

        if (!(assists.isEmpty())) {
            logger.info("取到待处理数据条数：" + assists.size());
            for (CpsTrans00700Assist order : assists) {
                String gopayOrderId = order.getGopayOrderId();
                try {

                    logger.info("处理数据开始gopayOrderid=" + gopayOrderId);
                    //更改发送装填

                    //update by dongdh 20170825 注销掉这里的状态
                    //  order.setStatus(Trans00700AssistStatus.SEND_CPS.value);
                  //  tran00700AssistDAO.update(order);

                    Tran00700AsyncVO vo = new Tran00700AsyncVO();
                    vo.setGopayOrderId(gopayOrderId);
                    vo.setOpType(PayBankAsyncOpType.CRON_FROM);
                    //调用cps
                    CPSResponse cpsResponse = callCPSHelper.callByVOTicket(vo);
                    String respCode = cpsResponse.getRespCode();

                    order = tran00700AssistDAO.find(CpsTrans00700Assist.class, gopayOrderId);
                   // order.setLastUpdTs(new Date());

                    //cps 返回 更改中间表 状态
                    if (!StringUtils.equals(ProcCodeConstants.PROC_CODE_100S1000, respCode)) {
                        logger.error("00700调用cps返回码异常respCode={}, gopayOrderId={}", respCode, gopayOrderId);
                       // order.setStatus(Trans00700AssistStatus.CPS_ERROR.value);
                       // order.setRemark(respCode);
                    } else {
                       // order.setStatus(Trans00700AssistStatus.SUCCESS.value);
                        logger.info("处理cps 调用 成功gopayOrderid=" + gopayOrderId);
                    }

                    //tran00700AssistDAO.update(order);
                } catch (GopayException e) {
                    logger.error("调用cps异常gopayOrderId=" + gopayOrderId , e);

                } catch (Exception e) {
                    logger.error("调用cps异常gopayOrderId=" + gopayOrderId , e);

                }
            }
        } else {
            logger.info("00700 取回列表为空...");
        }
    }

    public String getSwitch00700() {
        return switch00700;
    }

    public void setSwitch00700(String switch00700) {
        this.switch00700 = switch00700;
    }
}
